package com.sunday.fangbeibei.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.activity.CustomAddActivity;
import com.sunday.fangbeibei.activity.CustomDetailActivity;
import com.sunday.fangbeibei.adapter.CustomAdapter;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.CustomInfo;
import com.sunday.fangbeibei.widget.ActionSheet;
import com.sunday.fangbeibei.widget.ActionSheet.ActionSheetListener;
import com.sunday.fangbeibei.widget.CoPopupWindow;
import com.sunday.fangbeibei.widget.CoPopupWindow.OnPopupWindowClickListener;

/***
 * 

* @ClassName: CustomFragment 

* @Description: TODO(客户fragment) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年1月21日 上午10:54:56 

*
 */
public class CustomFragment extends Fragment implements OnItemClickListener,OnClickListener,ActionSheetListener,HttpResponseInterface,OnPopupWindowClickListener{

	private ListView listview;
	private Activity parent;
	private EditText searchet;
	private ImageView searchiv;

	private List<String> list;//cat
	
	private TextView title;
	
	private String status="";
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		parent=getActivity();
		
		listview=(ListView) getActivity().findViewById(R.id.listview);
		
		listview.setOnItemClickListener(this);
		ImageView add=(ImageView) getActivity().findViewById(R.id.add);
		
		searchet=(EditText) getActivity().findViewById(R.id.searchet);
		searchiv=(ImageView) getActivity().findViewById(R.id.searchiv);
		
		title=(TextView) getActivity().findViewById(R.id.title);
		title.setOnClickListener(this);
		
		searchiv.setOnClickListener(this);
		add.setOnClickListener(this);
		
	}
	
	
	

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(ApplicationCache.INSTANCE.getUserInfo().getType()!=3){
			loadData();
		}
	}




	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.custom_fragment, null);
	}
	
	
	private void loadData(){
		
		RequestParams params=new RequestParams();
		params.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
		params.add("key", searchet.getText().toString());
		params.add("filter_I_status", status);
		HttpTool.HttpPost(0, parent, ApplicationConstants.SERVER_URL+"/mobi/customer/searchcustomer", params, this, new TypeToken<BaseResult<List<CustomInfo>>>() {
		}.getType());
		
	}
	

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		Intent in=new Intent(getActivity(), CustomDetailActivity.class);
		CustomInfo info=(CustomInfo) view.getTag();
		in.putExtra("info", info);
		startActivity(in);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.add:
			getActivity().setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet.createBuilder(getActivity(), getActivity().getSupportFragmentManager())
			.setCancelButtonTitle("取消")
			.setOtherButtonTitles("从通讯录添加", "直接添加")
			.setCancelableOnTouchOutside(true).setListener(this).show();
			break;
		case R.id.searchiv:
			loadData();
			break;
		case R.id.title:
			CoPopupWindow co=new CoPopupWindow(parent);
			if(list==null){
				list=new ArrayList<String>();
				list.add("全部");
				list.add("未报备");
				list.add("已报备");
				list.add("申请带看");
				list.add("已带看");
				list.add("已成交");
				list.add("已结佣");
			}
			co.changeData(list);
			co.showAsDropDown(v,0,8);
			co.setOnPopupWindowClickListener(this);
			break;
		}
	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// TODO Auto-generated method stub
		if(index==0){
			 /*Intent i = new Intent(Intent.ACTION_PICK);                    
			 i.setType("vnd.android.cursor.dir/phone");                    
			 startActivityForResult(i, 123);*/
			 
			 Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
             startActivityForResult(intent, 123);
			 
		}else{
			Intent in=new Intent(getActivity(), CustomAddActivity.class);
			getActivity().startActivity(in);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==FragmentActivity.RESULT_OK){
			if(requestCode==123){
				
		        /* Uri contactData = data.getData(); 
		         Cursor c = getActivity().managedQuery(contactData, null, null, null, null); 
		         c.moveToFirst(); 
		         String number=c.getString(c.getColumnIndexOrThrow(Phones.NUMBER));
		         String name=c.getString(c.getColumnIndexOrThrow(Phones.NAME));
				 Intent in=new Intent(getActivity(), CustomAddActivity.class);
				 in.putExtra("name", name);
				 in.putExtra("phone", number);
				 getActivity().startActivity(in);*/
				
				 String username,usernumber="";
				
				 ContentResolver reContentResolverol = getActivity().getContentResolver();
	             Uri contactData = data.getData();
	             Cursor cursor = getActivity().managedQuery(contactData, null, null, null, null);
	             cursor.moveToFirst();
	             username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	             String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
	             Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
	             while (phone.moveToNext()) {
	                 usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	             }
				Intent in=new Intent(getActivity(), CustomAddActivity.class);
				in.putExtra("name", username);
				in.putExtra("phone", usernumber);
				getActivity().startActivity(in);
			}
		}
	}

	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		if(getActivity()==null){
			return;
		}
		switch(requsetCode){
		case 0:
			if(resultStatus){
				BaseResult<List<CustomInfo>> re=(BaseResult<List<CustomInfo>>) result;
				listview.setAdapter(new CustomAdapter(getActivity(),re.getResult()));
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		
	}




	@Override
	public void onPopupWindowItemClick(int position) {
		// TODO Auto-generated method stub
		title.setText(list.get(position));
		switch(position){
		case 0:
			status="";
			break;
		case 1:
			status="0";
			break;
		case 2:
			status="1";
			break;
		case 3:
			status="2";
			break;
		case 4:
			status="3";
			break;
		case 5:
			status="4";
			break;
		case 6:
			status="5";
			break;
		}
		loadData();
	}

	
}
